package org.bees.cms.web.action;

import java.util.Arrays;
import java.util.Enumeration;

import org.bees.cms.core.Domain;
import org.bees.cms.web.util.Beans;
import org.bees.cms.web.util.Pages;

public abstract class EditActionSupport<D extends Domain> extends ActionSupport<D> implements DomainAction<D>, ServiceAction<D> {
	public static final String UI = "ui";

	protected Long[] ids;
	protected D domain;

	@Override
	protected final String doExecute() throws Exception {
		return null;
	}

	public String ui() throws Exception {
		if (ids != null && ids.length > 0) {
			D domain = service().find(ids[0]);
			request.setAttribute(Pages.DOMAIN, domain);
		}
		return UI;
	}

	public String create() throws Exception {
		service().persist(domain);
		request.setAttribute(Pages.MESSAGE, "添加记录成功");
		return MESSAGE;
	}

	public String modify() throws Exception {
		if (domain.getId() == null || domain.getId() == 0) {
			return create();
		}
		D temp = service().find(domain.getId());
		Enumeration<?> enumeration = request.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String property = (String) enumeration.nextElement();
			if (property.startsWith("domain.")) {
				String name = property.substring(property.indexOf(".") + 1);
				Object value = Beans.get(domain, name);
				Beans.setProperty(temp, name, value);
			}
		}
		service().merge(temp);
		request.setAttribute(Pages.MESSAGE, "修改记录成功");
		return MESSAGE;
	}

	public String remove() throws Exception {
		if (ids != null && ids.length > 0) {
			service().remove(service().reference(Arrays.asList(ids)));
		}
		request.setAttribute(Pages.MESSAGE, "删除记录成功");
		return MESSAGE;
	}

	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

}
